package work.chenxr.restful.encrypt.advice;

import org.apache.commons.lang3.StringUtils;
import org.dromara.hutool.crypto.asymmetric.KeyType;
import org.dromara.hutool.crypto.asymmetric.RSA;
import org.dromara.hutool.crypto.symmetric.AES;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author Chenxr
 * @Date 2023/10/28
 * @Description
 */
public class DecryptHttpInputMessage implements HttpInputMessage {
    private final HttpHeaders headers;
    private final InputStream body;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage) throws IOException {
        this.headers = inputMessage.getHeaders();

        // 提取密文并去除首位 " 字符
        String content = StringUtils.removeEnd(
                StringUtils.removeStart(
                        new BufferedReader(new InputStreamReader(inputMessage.getBody())).readLine(),
                        "\""),
                "\"");

        if (content.startsWith("{")) {
            throw new RuntimeException("参数未加密");
        } else {
            //TODO 密钥可以配置在yml中，也可通过安全框架获取，例如：SecurityUser.getRsaPrivateKey()
            String rsaPrivateKey = "";
            RSA rsa = new RSA(rsaPrivateKey, null);

            // 获取通过RSA公钥加密后的AES密钥
            String aesSecretKey = this.headers.getFirst("secret-key");

            // RSA私钥解密AES密钥
            AES aes = new AES(rsa.decrypt(aesSecretKey, KeyType.PrivateKey));

            // AES解密
            String decryptBody = aes.decryptStr(content);

            this.body = new ByteArrayInputStream(decryptBody.getBytes(StandardCharsets.UTF_8));
        }
    }

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
